package com.waiting.leetcode;

/**
 * @Description
 * @Author bjweitingting
 * @Date 2019/3/25
 **/
public class CountBinarySubstrings696 {
    public static void main(String[] args) {
        String s = "10101";
        System.out.println(countBinarySubstrings(s));
    }

    public static int countBinarySubstrings(String s) {
        int sum = 0;
        int x = 0, y = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '1') {
                x++;
            }
            if (s.charAt(i) == '0') {
                y++;
            }
            if (x > 0 && y > 0 && (i == s.length() - 1 || s.charAt(i) != s.charAt(i + 1))) {
                sum += Math.min(x, y);
                if (s.charAt(i) == '1') {
                    y = 0;
                } else {
                    x = 0;
                }
            }
        }
        return sum;
    }
    public int countBinarySubstrings2(String s) {
        int prevRunLength = 0, curRunLength = 1, res = 0;
        for (int i=1;i<s.length();i++) {
            if (s.charAt(i) == s.charAt(i-1)) curRunLength++;
            else {
                prevRunLength = curRunLength;
                curRunLength = 1;
            }
            if (prevRunLength >= curRunLength) {
                res++;
            }
        }
        return res;
    }
}
